<template>
  <div>
    <div v-for="item in forms" class="form-item">
      <div class="title">{{item.label}}</div>
      <d-form :options="item.options" class="edit-form"/>
    </div>
    <el-button type="primary" class="submit-button" :color="formOptions.buttonColor" @click="submitForm" >提交
    </el-button>
  </div>
</template>

<script setup lang="ts">
  import {reactive, ref, watch} from 'vue'
  import {updateConfig} from '@/api/site'
  import {ElMessage, FormInstance} from "element-plus";
  import {communicationType,configType,targetType} from '@/utils/deviceConfig'
  import { cloneDeep } from 'lodash-es'

  let props = defineProps({
    options:{
      type:Object
    },
    params:{
      type:Object,
      default:{
        id:'',            // 站点的id/省份的code
        targetType:'',    // province 省份，device设备
      }         
    },
    config:{
      type:Object
    }
  });

  let formOptions = props.options;
  let form = reactive({  // 每个通道创建一个响应式对象（每个通道的字段一样）
    passageway1: {passagewayId: 1},
    passageway2: {passagewayId: 2},
    passageway3: {passagewayId: 3},
    passageway4: {passagewayId: 4},
    passageway5: {passagewayId: 5},
    passageway6: {passagewayId: 6},
  })

  const id = {
    label: '通道ID',
    prop: 'id',
    component: 'd-input',
    options: {
      placeholder: '请输入通道ID',
    },
    rules: {
      required: true,
      message: '请输入通道ID',
      trigger: 'change',
    },
    disabled: false
  }
  const options = {
    labelWidth: '160px',
    inline: formOptions.inline,
    labelPosition: formOptions.labelPosition,
    formRef: ref<FormInstance>(),
    formClass: formOptions.formClass,
    size: formOptions.size,
    formItems: [
      {
        label: '地震事件触发阈值(g)',
        prop: 'threshold',
        component: 'd-input',
        options: {
          placeholder: '请输入地震事件触发阈值',
          type: 'number'
        },
        rules: {
          required: true,
          message: '请输入地震事件触发阈值',
          trigger: 'change',
        },
        disabled: false
      },
      {
        label: '实时数据超限阈值(g)',
        prop: 'realtimeThreshold',
        component: 'd-input',
        options: {
          placeholder: '请输入实时数据超限阈值',
          type: 'number'
        },
        rules: {
          required: true,
          message: '请输入实时数据超限阈值',
          trigger: 'change',
        },
        disabled: false
      },
      {
        label: '偏置电压(V)',
        prop: 'biasVoltage',
        component: 'd-input',
        options: {
          placeholder: '请输入偏置电压',
          type: 'number'
        },
        rules: {
          required: true,
          message: '请输入偏置电压',
          trigger: 'change',
        },
        disabled: false
      },
      {
        label: '灵敏度(V/g)',
        prop: 'sensitivity',
        component: 'd-input',
        options: {
          placeholder: '请输入灵敏度',
          type: 'number'
        },
        rules: {
          required: true,
          message: '请输入灵敏度',
          trigger: 'change',
        },
        disabled: false
      }
    ],
    form: null
  }

 
  let forms = []
  watch(
    ()=>props.config,
    (val)=>{
      if(val.passageways){
        let result = val.passageways
        for(let i=0,l=result.length;i<l;i++){
          let item = result[i]
          for(let key in form){
            if(item.passagewayId===form[key].passagewayId){
              form[key] = Object.assign(form[key],item)
              console.log(form[key])
              break;
            }
          }
        }
        forms = []
        let index = 1;
        for (let key in form) {
          forms.push({
            label: '通道' + index++,
            options: {...options, ...{form: form[key]}}
          })
        }
      }
    },
    {
      deep:true
    }
  )

  const handleParamsData = ()=>{
    return forms.map(v=>{
      return v.options.form
    })
  }
  
  const submitForm = async () => {
    let formEl = options.formRef?.value;
    if (!formEl) return
    await formEl.validate((valid, fields) => {
      if (valid) {
        updateData( handleParamsData())
      }
    })
  }
  type paramsType = {
    configType:number,
    id:string,
    targetType:string,
    [propName:string]:any,
  }
  const updateData = (data)=>{
    let params:paramsType = {
      configType:configType['passageway'],
      id:props.params.id,
      targetType:targetType[props.params.targetType],
      passageway: {passageways:data}
    }
    updateConfig(params).then(res=>{
      ElMessage.success('更新成功！')
    })
  }

  const resetForm = () => {
    let formEl = options.formRef?.value;
    if (!formEl) return
    formEl.resetFields()
  }


</script>
